'use client';

// 文件管理页面
// REF: API-USER-0042@v2.0

import React, { useEffect, useState } from 'react';
import {
  FolderOpen,
  FileText,
  Upload,
  FolderPlus,
  Search,
  ArrowLeft,
  ArrowRight,
  ArrowUp,
  Copy,
  Move,
  Trash2,
  Clipboard,
  FileType,
  Calendar,
  Star,
  StarOff,
  MoreHorizontal,
  Download,
  Share2,
  Image as ImageIcon,
  Video,
  Music,
  Archive,
  RefreshCw
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbSeparator } from '@/components/ui/breadcrumb';
import { driveApi, NetdiskFile } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import { useConfirmDialog } from '@/components/ui/confirm-dialog';
import { useInputDialog } from '@/components/ui/input-dialog';
import UploadDialog from '@/components/upload/UploadDialog';

// 使用NetdiskFile作为主要接口
type FileItem = NetdiskFile;

type SortBy = 'name' | 'modified' | 'size' | 'type';
type FileTypeFilter = 'all' | 'image' | 'video' | 'audio' | 'document' | 'archive';

interface ClipboardItem {
  files: FileItem[];
  operation: 'copy' | 'cut';
}

interface FolderNode {
  id: number;
  name: string;
  parentId?: number;
}

function getFileIcon(fileName: string, isFolder: boolean) {
  if (isFolder) {
    return FolderOpen;
  }
  
  const extension = fileName.split('.').pop()?.toLowerCase();
  
  switch (extension) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'webp':
      return ImageIcon;
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
      return Video;
    case 'mp3':
    case 'wav':
    case 'flac':
      return Music;
    case 'zip':
    case 'rar':
    case '7z':
      return Archive;
    default:
      return FileText;
  }
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - date.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays === 1) {
    return '今天';
  } else if (diffDays === 2) {
    return '昨天';
  } else if (diffDays <= 7) {
    return `${diffDays - 1}天前`;
  } else {
    return typeof window !== 'undefined' ? date.toLocaleDateString() : date.toISOString().split('T')[0];
  }
}

export default function FilesPage() {
  const { toast } = useToast();
  const { showConfirm, ConfirmDialog } = useConfirmDialog();
  const { showInput, InputDialog } = useInputDialog();
  
  // 状态管理
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [sortBy, setSortBy] = useState<SortBy>('name');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedFiles, setSelectedFiles] = useState<Set<number>>(new Set());
  const [currentPath, setCurrentPath] = useState<FolderNode[]>([{ id: 0, name: '根目录' }]);
  const [currentFolderId, setCurrentFolderId] = useState<number | undefined>(undefined);
  const [fileTypeFilter, setFileTypeFilter] = useState<FileTypeFilter>('all');
  const [clipboard, setClipboard] = useState<ClipboardItem | null>(null);
  const [navigationHistory, setNavigationHistory] = useState<number[]>([0]);
  const [historyIndex, setHistoryIndex] = useState(0);
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);

  // 加载文件列表
  const loadFiles = React.useCallback(async (folderId?: number) => {
    setLoading(true);
    try {
      const response = await driveApi.getFiles(folderId);
      if (response.success) {
        setFiles(response.data.files);
      } else {
        toast({
          title: '加载失败',
          description: response.message || '获取文件列表失败',
          variant: 'destructive'
        });
      }
    } catch (error) {
      console.error('加载文件失败:', error);
      toast({
        title: '加载失败',
        description: '网络错误，请稍后重试',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  }, [toast]);

  // 初始加载和文件夹变化时重新加载
  React.useEffect(() => {
    loadFiles(currentFolderId);
  }, [currentFolderId, loadFiles]);

  // 获取文件类型
  const getFileType = (fileName: string, isFolder: boolean): FileTypeFilter => {
    if (isFolder) return 'all';
    const ext = fileName.split('.').pop()?.toLowerCase() || '';
    
    if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(ext)) return 'image';
    if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'].includes(ext)) return 'video';
    if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(ext)) return 'audio';
    if (['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'].includes(ext)) return 'document';
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'archive';
    
    return 'all';
  };

  // 筛选和排序文件
  const filteredAndSortedFiles = React.useMemo(() => {
    if (!files || !Array.isArray(files)) {
      return [];
    }
    
    let filtered = files.filter(file => {
      // 搜索筛选
      const matchesSearch = file.name.toLowerCase().includes(searchTerm.toLowerCase());
      
      // 文件类型筛选
      const isFolder = file.type === 'folder';
      const matchesType = fileTypeFilter === 'all' || 
        isFolder || 
        getFileType(file.name, isFolder) === fileTypeFilter;
      
      return matchesSearch && matchesType;
    });

    // 排序
    filtered.sort((a, b) => {
      // 文件夹优先
      const aIsFolder = a.type === 'folder';
      const bIsFolder = b.type === 'folder';
      if (aIsFolder && !bIsFolder) return -1;
      if (!aIsFolder && bIsFolder) return 1;
      
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'modified':
          return new Date(b.modified).getTime() - new Date(a.modified).getTime();
        case 'size':
          return (b.size || 0) - (a.size || 0);
        case 'type':
          return a.name.localeCompare(b.name);
        default:
          return 0;
      }
    });

    return filtered;
  }, [files, searchTerm, sortBy, fileTypeFilter]);

  // 导航功能
  const canGoBack = () => historyIndex > 0;
  const canGoForward = () => historyIndex < navigationHistory.length - 1;
  
  const goBack = () => {
    if (canGoBack()) {
      const newIndex = historyIndex - 1;
      setHistoryIndex(newIndex);
      const folderId = navigationHistory[newIndex];
      setCurrentFolderId(folderId === 0 ? undefined : folderId);
      // 更新面包屑路径
    }
  };
  
  const goForward = () => {
    if (canGoForward()) {
      const newIndex = historyIndex + 1;
      setHistoryIndex(newIndex);
      const folderId = navigationHistory[newIndex];
      setCurrentFolderId(folderId === 0 ? undefined : folderId);
      // 更新面包屑路径
    }
  };
  
  const goUp = () => {
    if (currentPath.length > 1) {
      const parentFolder = currentPath[currentPath.length - 2];
      const newPath = currentPath.slice(0, -1);
      setCurrentPath(newPath);
      setCurrentFolderId(parentFolder.id === 0 ? undefined : parentFolder.id);
      
      // 更新导航历史
      const newHistory = navigationHistory.slice(0, historyIndex + 1);
      newHistory.push(parentFolder.id);
      setNavigationHistory(newHistory);
      setHistoryIndex(newHistory.length - 1);
    }
  };

  // 选择文件
  const toggleFileSelection = (fileId: number) => {
    const newSelected = new Set(selectedFiles);
    if (newSelected.has(fileId)) {
      newSelected.delete(fileId);
    } else {
      newSelected.add(fileId);
    }
    setSelectedFiles(newSelected);
  };
  
  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedFiles.size === filteredAndSortedFiles.length) {
      setSelectedFiles(new Set());
    } else {
      setSelectedFiles(new Set(filteredAndSortedFiles.map(f => f.id)));
    }
  };

  // 文件操作
  const handleFileAction = async (action: string, fileId?: number) => {
    const targetFiles = fileId ? [fileId] : Array.from(selectedFiles);
    
    switch (action) {
      case 'copy':
        if (targetFiles.length > 0) {
          const filesToCopy = files.filter(f => targetFiles.includes(f.id));
          setClipboard({ files: filesToCopy, operation: 'copy' });
          toast({
            title: '已复制',
            description: `已复制 ${filesToCopy.length} 个项目到剪贴板`
          });
        }
        break;
      case 'cut':
        if (targetFiles.length > 0) {
          const filesToCut = files.filter(f => targetFiles.includes(f.id));
          setClipboard({ files: filesToCut, operation: 'cut' });
          toast({
            title: '已剪切',
            description: `已剪切 ${filesToCut.length} 个项目到剪贴板`
          });
        }
        break;
      case 'paste':
        if (clipboard) {
          try {
            for (const file of clipboard.files) {
              if (clipboard.operation === 'copy') {
                await driveApi.copyFile(file.id, currentFolderId);
              } else {
                await driveApi.moveFile(file.id, currentFolderId);
              }
            }
            
            toast({
              title: '操作成功',
              description: `已${clipboard.operation === 'copy' ? '复制' : '移动'} ${clipboard.files.length} 个项目`
            });
            
            setClipboard(null);
            setSelectedFiles(new Set());
            loadFiles(currentFolderId);
          } catch (error) {
            console.error('粘贴失败:', error);
            toast({
              title: '操作失败',
              description: '粘贴操作失败，请稍后重试',
              variant: 'destructive'
            });
          }
        }
        break;
      case 'delete':
        if (targetFiles.length === 0) return;
        
        showConfirm({
          title: '确认删除',
          description: `确定要删除选中的 ${targetFiles.length} 个项目吗？删除后无法恢复。`,
          confirmText: '删除',
          cancelText: '取消',
          variant: 'destructive',
          onConfirm: async () => {
            try {
              const response = await driveApi.deleteFiles(Array.from(targetFiles));
              
              if (response.success) {
                toast({
                  title: '删除成功',
                  description: `已删除 ${targetFiles.length} 个项目`
                });
                
                setSelectedFiles(new Set());
                loadFiles(currentFolderId);
              } else {
                throw new Error(response.message || '删除失败');
              }
            } catch (error) {
              console.error('删除失败:', error);
              toast({
                title: '删除失败',
                description: error instanceof Error ? error.message : '删除操作失败，请稍后重试',
                variant: 'destructive'
              });
            }
          }
        });
        break;
      case 'download':
        if (fileId) {
          try {
            const response = await driveApi.getDownloadLink(fileId);
            if (response.success && response.data) {
              window.open(response.data.downloadUrl, '_blank');
            } else {
              toast({
                title: '下载失败',
                description: response.message || '获取下载链接失败',
                variant: 'destructive'
              });
            }
          } catch (error) {
            console.error('下载失败:', error);
            toast({
              title: '下载失败',
              description: '网络错误，请稍后重试',
              variant: 'destructive'
            });
          }
        }
        break;
      case 'share':
        toast({
          title: '分享功能',
          description: '分享功能正在开发中'
        });
        break;
      case 'favorite':
        if (fileId) {
          try {
            setFiles(prev => prev.map(f => 
              f.id === fileId ? { ...f, favorite: !f.favorite } : f
            ));
          } catch (error) {
            console.error('收藏操作失败:', error);
          }
        }
        break;
      default:
        console.log(`执行操作: ${action}`, targetFiles);
    }
  };
  
  // 创建文件夹
  const createFolder = async () => {
    showInput({
      title: '创建文件夹',
      description: '请输入文件夹名称',
      placeholder: '文件夹名称',
      confirmText: '创建',
      cancelText: '取消',
      onConfirm: async (folderName: string) => {
        try {
          const response = await driveApi.createFolder(folderName, currentFolderId);
          if (response.success) {
            toast({
              title: '创建成功',
              description: `文件夹 "${folderName}" 创建成功`
            });
            loadFiles(currentFolderId);
          } else {
            toast({
              title: '创建失败',
              description: response.message || '创建文件夹失败',
              variant: 'destructive'
            });
          }
        } catch (error) {
          console.error('创建文件夹失败:', error);
          toast({
            title: '创建失败',
            description: '网络错误，请稍后重试',
            variant: 'destructive'
          });
        }
      }
    });
  };
  
  // 上传文件
  const uploadFiles = async () => {
    setUploadDialogOpen(true);
  };

  // 刷新文件列表
  const refreshFiles = () => {
    loadFiles(currentFolderId);
    toast({
      title: '刷新成功',
      description: '文件列表已更新'
    });
  };

  // 上传完成回调
  const handleUploadComplete = () => {
    loadFiles(currentFolderId);
  };
  
  // 重命名逻辑（Windows风格）
  const generateNewName = (originalName: string, existingNames: string[]): string => {
    if (!existingNames.includes(originalName)) {
      return originalName;
    }
    
    const ext = originalName.includes('.') ? '.' + originalName.split('.').pop() : '';
    const baseName = ext ? originalName.slice(0, -ext.length) : originalName;
    
    let counter = 1;
    let newName: string;
    
    do {
      newName = `${baseName} (${counter})${ext}`;
      counter++;
    } while (existingNames.includes(newName));
    
    return newName;
  };

  // 导航到文件夹
  const navigateToFolder = (folderId: number, folderName: string) => {
    const newFolder: FolderNode = {
      id: folderId,
      name: folderName,
      parentId: currentFolderId
    };
    
    const newPath = [...currentPath, newFolder];
    setCurrentPath(newPath);
    setCurrentFolderId(folderId);
    
    // 更新导航历史
    const newHistory = navigationHistory.slice(0, historyIndex + 1);
    newHistory.push(folderId);
    setNavigationHistory(newHistory);
    setHistoryIndex(newHistory.length - 1);
  };

  // 文件列表表格组件
  const FileTable = () => {
    const isAllSelected = selectedFiles.size === filteredAndSortedFiles.length && filteredAndSortedFiles.length > 0;
    const isIndeterminate = selectedFiles.size > 0 && selectedFiles.size < filteredAndSortedFiles.length;

    const handleSelectAll = () => {
      if (isAllSelected) {
        setSelectedFiles(new Set());
      } else {
        setSelectedFiles(new Set(filteredAndSortedFiles.map(f => f.id)));
      }
    };

    const handleFileSelect = (fileId: number, checked: boolean) => {
      const newSelected = new Set(selectedFiles);
      if (checked) {
        newSelected.add(fileId);
      } else {
        newSelected.delete(fileId);
      }
      setSelectedFiles(newSelected);
    };

    const handleFileClick = (file: FileItem) => {
      if (file.type === 'folder') {
        navigateToFolder(file.id, file.name);
      }
    };

    return (
      <div className="border rounded-lg overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 border-b">
            <tr>
              <th className="w-12 p-3 text-left">
                <input
                  type="checkbox"
                  checked={isAllSelected}
                  ref={(el) => {
                    if (el) el.indeterminate = isIndeterminate;
                  }}
                  onChange={handleSelectAll}
                  className="rounded"
                />
              </th>
              <th className="p-3 text-left font-medium text-gray-900">文件名</th>
              <th className="p-3 text-left font-medium text-gray-900 w-24">大小</th>
              <th className="p-3 text-left font-medium text-gray-900 w-20">收藏</th>
              <th className="p-3 text-left font-medium text-gray-900 w-32">修改时间</th>
              <th className="p-3 text-left font-medium text-gray-900 w-24">操作</th>
            </tr>
          </thead>
          <tbody>
            {filteredAndSortedFiles.map((file) => {
              const isFolder = file.type === 'folder';
              const Icon = getFileIcon(file.name, isFolder);
              const isSelected = selectedFiles.has(file.id);
              
              return (
                <tr 
                  key={file.id} 
                  className={`border-b hover:bg-gray-50 transition-colors cursor-pointer ${
                    isSelected ? 'bg-blue-50' : ''
                  }`}
                  onClick={() => handleFileClick(file)}
                >
                  <td className="p-3" onClick={(e) => e.stopPropagation()}>
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedFiles(prev => new Set([...prev, file.id]));
                        } else {
                          setSelectedFiles(prev => {
                            const newSet = new Set(prev);
                            newSet.delete(file.id);
                            return newSet;
                          });
                        }
                      }}
                      className="rounded"
                    />
                  </td>
                  <td className="p-3">
                    <div className="flex items-center gap-3">
                      <div className={`p-2 rounded-lg ${
                        isFolder ? 'bg-blue-100' : 'bg-gray-100'
                      }`}>
                        <Icon className={`h-5 w-5 ${
                          isFolder ? 'text-blue-600' : 'text-gray-600'
                        }`} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium truncate" title={file.name}>
                          {file.name}
                        </p>
                        {file.shared && (
                          <Badge variant="outline" className="text-xs mt-1">
                            <Share2 className="h-3 w-3 mr-1" />
                            共享
                          </Badge>
                        )}
                      </div>
                    </div>
                  </td>
                  <td className="p-3 text-sm text-gray-600">
                    {isFolder ? '-' : formatBytes(file.size || 0)}
                  </td>
                  <td className="p-3" onClick={(e) => e.stopPropagation()}>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleFileAction('favorite', file.id)}
                      className="h-8 w-8 p-0"
                    >
                      {file.favorite ? (
                        <Star className="h-4 w-4 text-yellow-500 fill-current" />
                      ) : (
                        <StarOff className="h-4 w-4 text-gray-400" />
                      )}
                    </Button>
                  </td>
                  <td className="p-3 text-sm text-gray-600">
                    {formatDate(file.modified)}
                  </td>
                  <td className="p-3" onClick={(e) => e.stopPropagation()}>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuLabel>操作</DropdownMenuLabel>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={() => handleFileAction('download', file.id)}>
                          <Download className="mr-2 h-4 w-4" />
                          下载
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleFileAction('copy', file.id)}>
                          <Copy className="mr-2 h-4 w-4" />
                          复制
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleFileAction('cut', file.id)}>
                          <Move className="mr-2 h-4 w-4" />
                          剪切
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleFileAction('share', file.id)}>
                          <Share2 className="mr-2 h-4 w-4" />
                          共享
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem 
                          className="text-red-600"
                          onClick={() => handleFileAction('delete', file.id)}
                        >
                          <Trash2 className="mr-2 h-4 w-4" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  };

  return (
    <div className="p-6 space-y-4">
      {/* 第一行工具栏：快捷键 + 目录 + 搜索 */}
      <div className="flex items-center justify-between gap-4">
        {/* 快捷键 */}
        <div className="flex items-center gap-2">
          <Button 
            variant="outline" 
            size="sm" 
            onClick={goBack}
            disabled={!canGoBack()}
            title="后退"
          >
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <Button 
            variant="outline" 
            size="sm" 
            onClick={goForward}
            disabled={!canGoForward()}
            title="前进"
          >
            <ArrowRight className="h-4 w-4" />
          </Button>
          <Button 
            variant="outline" 
            size="sm" 
            onClick={goUp}
            disabled={currentPath.length <= 1}
            title="上级"
          >
            <ArrowUp className="h-4 w-4" />
          </Button>
          <Button 
            variant="outline" 
            size="sm" 
            onClick={refreshFiles}
            title="刷新"
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>

        {/* 面包屑导航 */}
        <div className="flex-1 mx-4">
          <Breadcrumb>
            <BreadcrumbList>
              {currentPath.map((path, index) => (
                <React.Fragment key={index}>
                  <BreadcrumbItem>
                    <BreadcrumbLink href="#" className="text-blue-600">
                      {path.name}
                    </BreadcrumbLink>
                  </BreadcrumbItem>
                  {index < currentPath.length - 1 && <BreadcrumbSeparator />}
                </React.Fragment>
              ))}
            </BreadcrumbList>
          </Breadcrumb>
        </div>

        {/* 搜索 */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
          <Input
            placeholder="搜索文件..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 w-64"
          />
        </div>
      </div>

      {/* 第二行工具栏：新建 + 上传 + 操作按钮 + 搜索功能 */}
      <div className="flex items-center justify-between gap-4">
        {/* 左侧：新建和上传 */}
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button>
                <FolderPlus className="h-4 w-4 mr-2" />
                新建
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent>
              <DropdownMenuItem onClick={createFolder}>
                <FolderPlus className="mr-2 h-4 w-4" />
                新建文件夹
              </DropdownMenuItem>
              <DropdownMenuItem>
                <FileText className="mr-2 h-4 w-4" />
                新建文件
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
          
          <Button onClick={uploadFiles}>
            <Upload className="h-4 w-4 mr-2" />
            上传
          </Button>
        </div>

        {/* 中间：操作按钮 */}
        <div className="flex items-center gap-2">
          <Button 
            variant="outline" 
            size="sm" 
            onClick={() => handleFileAction('copy')}
            disabled={selectedFiles.size === 0}
          >
            <Copy className="h-4 w-4 mr-2" />
            复制
          </Button>
          <Button 
            variant="outline" 
            size="sm" 
            onClick={() => handleFileAction('cut')}
            disabled={selectedFiles.size === 0}
          >
            <Move className="h-4 w-4 mr-2" />
            移动
          </Button>
          <Button 
            variant="outline" 
            size="sm" 
            onClick={() => handleFileAction('delete')}
            disabled={selectedFiles.size === 0}
            className="text-red-600"
          >
            <Trash2 className="h-4 w-4 mr-2" />
            删除
          </Button>
          
          <div className="h-6 w-px bg-gray-300 mx-2" />
          
          <Button 
            variant="outline" 
            size="sm" 
            onClick={() => handleFileAction('paste')}
            disabled={!clipboard}
          >
            <Clipboard className="h-4 w-4 mr-2" />
            粘贴
          </Button>
          
          {selectedFiles.size > 0 && (
            <span className="text-sm text-gray-600 ml-2">
              已选中 {selectedFiles.size} 项
            </span>
          )}
        </div>

        {/* 右侧：搜索功能 */}
        <div className="flex items-center gap-2">
          <Select value={fileTypeFilter} onValueChange={(value: FileTypeFilter) => setFileTypeFilter(value)}>
            <SelectTrigger className="w-32">
              <FileType className="h-4 w-4 mr-2" />
              <SelectValue placeholder="文件类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">所有文件</SelectItem>
              <SelectItem value="image">图片</SelectItem>
              <SelectItem value="video">视频</SelectItem>
              <SelectItem value="audio">音频</SelectItem>
              <SelectItem value="document">文档</SelectItem>
              <SelectItem value="archive">压缩包</SelectItem>
            </SelectContent>
          </Select>
          
          <Select value={sortBy} onValueChange={(value: SortBy) => setSortBy(value)}>
            <SelectTrigger className="w-32">
              <Calendar className="h-4 w-4 mr-2" />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="name">名称</SelectItem>
              <SelectItem value="modified">修改时间</SelectItem>
              <SelectItem value="size">大小</SelectItem>
              <SelectItem value="type">类型</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 文件列表 */}
      {loading ? (
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载中...</p>
        </div>
      ) : filteredAndSortedFiles.length === 0 ? (
        <Card>
          <CardContent className="pt-12 pb-12 text-center">
            <FolderOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无文件</h3>
            <p className="text-gray-600 mb-4">
              {searchTerm || fileTypeFilter !== 'all' ? '没有找到匹配的文件' : '这个文件夹是空的'}
            </p>
            {!searchTerm && fileTypeFilter === 'all' && (
              <Button onClick={uploadFiles}>
                <Upload className="h-4 w-4 mr-2" />
                上传第一个文件
              </Button>
            )}
          </CardContent>
        </Card>
      ) : (
        <FileTable />
      )}
      <ConfirmDialog />
      <InputDialog />
      <UploadDialog 
        open={uploadDialogOpen}
        onOpenChange={setUploadDialogOpen}
        currentFolderId={currentFolderId}
        onUploadComplete={handleUploadComplete}
      />
    </div>
  );
}